<?php

/**
 * message actions.
 *
 * @package    maximous
 * @subpackage message
 * @author     Mina.Gerges.Wadea
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class messageActions extends MaxFrontendActions
{

    public function preExecute()
    {
        parent::preExecute();
        $this->maxUser->getMaxUserRole()->setDefaultSiteComponent(SiteComponent::Message);
    }

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request)
    {
        
    }

    public function executeShowMessages(sfWebRequest $request)
    {
        // request by ajax
        $this->forward404Unless($request->isXmlHttpRequest());
        $type = $request->getParameter('type');
        // the type should be 'send' or 'receive'
        $this->forward404Unless($type == 'send' || $type == 'receive');
        if ($type == 'send')
        {
            $query = MessageTable::getInstance()->getSendedMessagesoFUser($this->maxUser->getUserDataByIndex('id'));
        }
        else
        {
            $query = MessageTable::getInstance()->getReceivedMessagesOfUser($this->maxUser->getUserDataByIndex('id'));
        }
        $page  = $request->getParameter('page', 1);
        $this->pager = $this->createPager('Message', $query, $page, sfConfig::get('app_messages_per_page'));
    }

    public function executeSendMessage(sfWebRequest $request)
    {
        $this->forward404Unless($this->maxUser->getMaxUserRole()->canAdd());
        $messageForm = new MessageForm(null, array('i18n'    => $this->i18n, 'maxUser' => $this->maxUser));
        $messageForm->removeToUserFiled();
        $valid    = '';
        $html     = '';
        if ($request->isMethod(sfWebRequest::POST))
        {
            $messageForm->bind($request->getParameter($messageForm->getName()));
            if ($messageForm->isValid())
            {
                $messageForm->save();
                $valid = true;
            }
        }
        if (!$valid)
        {
            $html = $this->getPartial('sendMessageForm', array('messageForm' => $messageForm));
        }
        return $this->renderJson(array('html'  => $html, 'valid' => $valid));
    }

}
